<template>
  <div class="role">
    <hzhy-data-table ref="dataTable" v-bind="tableConfig">
      <template slot="left-btn">
        <el-button type="primary" icon="el-icon-plus" plain @click="handleRowUpdate('add')">
          添加
        </el-button>
      </template>
    </hzhy-data-table>
    <common-dialog-form
      ref="commonDrawerForm"
      :visible.sync="visible"
      :title="drawerTitle"
      :content="formContent"
      :onConfirm="onConfirm"
    ></common-dialog-form>
  </div>
</template>

<script>
import CommonDialogForm from '@/components/common-dialog-form'
import AttachmentConfig from '@/container/configure/file/attachment-config'
import * as api from '@/const/api'

export default {
  title: '文件下载管理',
  name: 'ConfigureFile',
  components: {
    CommonDialogForm,
  },
  data() {
    return {
      tableConfig: {
        url: api.attachmentInfoPage,
        columns: [
          {
            label: '序号',
            type: 'index',
            prop: 'index',
            fixed: 'left',
          },
          {
            label: '名称（中文）',
            prop: 'nameZh',
          },
          {
            label: '名称（英文）',
            prop: 'nameEn',
          },
          {
            label: '型号（中文）',
            prop: 'typeZh',
          },
          {
            label: '型号（英文）',
            prop: 'typeEn',
          },
          {
            label: '创建时间',
            prop: 'createTime',
          },
          {
            label: '操作',
            prop: 'operation',
            width: 280,
            fixed: 'right',
            setBtns: (row) => {
              const btns = [
                {
                  label: '编辑',
                  handler: () => {
                    this.handleRowUpdate('edit', row)
                  },
                },
                {
                  label: '删除',
                  className: 'red',
                  handler: () => {
                    this.handleRowDelete(row)
                  },
                },
                {
                  label: '分配资源',
                  handler: () => {
                    this.handleConfigRole(row)
                  },
                },
                {
                  label: '角色人员查看',
                  className: '',
                  handler: () => {
                    this.handleRowView(row)
                  },
                },
              ]
              return this.$ac.operationAccess(btns)
            },
          },
        ],
        searchForm: [
          {
            $type: 'input',
            $id: 'nameZh',
            label: '文件名称',
            $el: {
              clearable: true,
              placeholder: '请输入',
            },
          },
        ],
      },
      visible: false,
      currentRow: {}, // 当前编辑项
    }
  },
  computed: {
    // 编辑还是新增
    isEdit() {
      return !!this.currentRow.id
    },
    // 侧边栏表单标题
    drawerTitle() {
      return this.isEdit ? '编辑' : '新增'
    },
    formContent() {
      return [
        {
          $id: 'nameZh',
          $type: 'input',
          label: '名称（中文）',
          $el: {
            placeholder: '请输入名称（中文）',
            clearable: true,
            maxLength: 100,
          },
          rules: [{ required: true, message: '请输入名称（中文）', trigger: 'change' }],
        },
        {
          $id: 'nameEn',
          $type: 'input',
          label: '名称（英文）',
          $el: {
            placeholder: '请输入名称（英文）',
            clearable: true,
            maxlength: 100,
            showWordLimit: true,
          },
          rules: [{ required: true, message: '请输入名称（英文）', trigger: 'change' }],
        },
        {
          $id: 'typeZh',
          $type: 'input',
          label: '型号（中文）',
          $el: {
            placeholder: '请输入型号（中文）',
            clearable: true,
            maxLength: 100,
          },
          rules: [{ required: true, message: '请输入型号（中文）', trigger: 'change' }],
        },
        {
          $id: 'typeEn',
          $type: 'input',
          label: '型号（英文）',
          $el: {
            placeholder: '请输入型号（英文）',
            clearable: true,
            maxlength: 100,
            showWordLimit: true,
          },
          rules: [{ required: true, message: '请输入型号（英文）', trigger: 'change' }],
        },
        {
          $id: 'attachment',
          label: '附件',
          component: AttachmentConfig,
          class: 'w-1-1',
          $el: {},
          inputFormat: ({ attachment }) => {
            if (!attachment) {
              return {}
            }
            return JSON.parse(attachment)
          },
          outputFormat: (val) => {
            if (!val) {
              return
            }
            return JSON.stringify(val)
          },
        },
      ]
    },
  },
  methods: {
    // 侧边栏form确认回调
    async onConfirm(data) {
      try {
        const params = {
          ...data,
        }
        // 编辑需要加上id参数
        if (this.isEdit) {
          params.id = this.currentRow.id
        }

        let res = ''

        if (this.isEdit) {
          res = await this.$axios.$put(api.attachmentInfo, params)
        } else {
          res = await this.$axios.$post(api.attachmentInfo, params)
        }

        const { code, msg } = res
        if (+code !== 200) {
          throw new Error(msg || '操作失败')
        }

        this.$message.success('操作成功')
        this.$refs.dataTable.goPage() // 刷新界面
      } catch (err) {
        this.$message.error(err.message)
      }
    },
    // 打开侧边栏form弹层
    handleRowUpdate(type, row) {
      this.visible = true
      if (type === 'edit') {
        this.currentRow = row
        this.$refs.commonDrawerForm.updateForm(row)
      } else {
        this.currentRow = {}
      }
    },
    async handleRowDelete(row) {
      let loading = ''
      try {
        const isFlag = await this.$confirm('确认删除？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
        if (isFlag !== 'confirm') {
          return
        }
        loading = this.$loading({
          text: 'Loading',
          spinner: 'el-icon-loading',
        })
        const { code, msg } = await this.$axios.$delete(`${api.attachmentInfo}/${row.id}`)
        if (+code !== 200) {
          throw new Error(msg || '操作失败')
        }
        this.$message.success('操作成功')
        this.$refs.dataTable.goPage() // 刷新界面
      } catch (err) {
        err.message && this.$message.error(err.message)
      } finally {
        loading && loading.close()
      }
    },
  },
}
</script>
<style lang="less" scoped>
.index {
  position: relative;
  width: calc(100vw - 106px);
  height: calc(100vh - 154px);
  background-color: #fff;
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center center;
}
</style>
